package com.pf.messageQueue.service.impl;

import com.google.common.collect.Lists;
import com.pf.messageQueue.service.RedisMessageQueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisMessageQueueServiceImpl implements RedisMessageQueueService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String LIST_KEY = "MESSAGE_LIST_QUEUE_KEY";

    @Override
    public void lpush() {
        List<Integer> data = Lists.newArrayList(1, 2, 3, 4, 5, 6);
        // 循环5组，每组放入 1 至 6 这六个数字
        for (int i = 0; i < 5; i++) {
            redisTemplate.opsForList().leftPushAll(LIST_KEY, data);
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(">>>>> 生产者生产数据完毕!");
    }

    @Override
    public void rpop() {
        while (true) {
            // 每隔一秒钟取出一个数据
            Integer num = (Integer) redisTemplate.opsForList().rightPop(LIST_KEY);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (num != null) {
                System.out.println(">>>>> 消费者消费数字=" + num);
            }
        }

    }
}
